package com.shangke.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ChatRoom implements Runnable{
	private Socket socked=null;
	private Map<String, Socket> clientMap=new Hashtable<String, Socket>();
	
	public ChatRoom(Socket socket,Map<String, Socket> clientMap) {
		this.socked=socket;
		this.clientMap=clientMap;
	}

	@Override
	public void run() {
		InputStream inputStream=null;
		
		while(true){
			try {
				inputStream=socked.getInputStream();
				
				byte[] buffer=new byte[512];
				int len=inputStream.read(buffer);
				String words=new String(buffer, 0, len);
				if ("quit".equalsIgnoreCase(words)) {  //trim() 客户端发生的内容可能包含有回车键或其它特殊符号
					break;
				}
				
				Set<String> keySet=clientMap.keySet();
				Iterator<String> iterator=keySet.iterator();
				Socket socket = null;
				String client = null;
				OutputStream outputStream = null;

				
				while(iterator.hasNext()){
					String clientIp=iterator.next();
					try {
						if (clientIp != socked.getInetAddress().getHostAddress()) {
							socket=clientMap.get(clientIp);
							outputStream=socket.getOutputStream();
							
							String reply=socket.getInetAddress().getHostAddress()+":"+words;
							outputStream.write(reply.getBytes());
						}
					} catch (Exception e) {
						if (socked == null || socked.isClosed()) {
							clientMap.remove(client);
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
